//参数
var url = 'http://localhost:8002';
var opts = {
	// canvas存放的父节点
	elem: '.fit-canvas',
	// 模特当前体型
	BMIType: 'norm',
	// 试衣间大小
	somato: {
		height: 180,
		weight: 70
	},
	// 当前是第几面
	rotateType: 0,
	// 性别
	sex: 'woman',
	// 试衣间规格
	cvsWidth: 780,
	cvsHeight: 950,
	// 试衣间默认图片
	images: {
		// 身体
		bodySrc: {
			head: url+'/images/woman/head1.png',
			body: url+'/images/woman/body1.png'
		},
		// 配饰
		accSrc: {
			shoes : url+'/images/woman/shoes1.png'
		},
		// 
		nSrc: { 
			knicker: url+'/images/wClothes/star/bras3_1.png'
		},
		//
		shirtSrc : {
			shirt: url+'/images/wClothes/jy/shirt0_1.png'
		},
		coatSrc : {
			coat: ''
		},
		trouserSrc : {
			trouser: url+'/images/wClothes/jy/skirt0_1.png'
		},
	}
};

//记录点
var markArr = [];
var mark = function(x, y, size, color) {
	this.x = x;
	this.y = y;
	this.size = size;
	this.color = color;
}

//记录图片
var textures = {};
var texture = [];
var allNorm = {};
var allSfat = {};
var allFat = {};

//元素
var $elem1, $elem2, $elem3;

// 加载的面
var renderNum = 0;

//画布的 宽、高
var cvsWidth;
var cvsHeight;

//最终画布
var cWidth;
var cHeight;

/*
 *	  画布和模特的比率：
 *   画布上下空各余出20像素
 *  (cvsHeight - 40) / 182
 */
var rate = 5.6;

/*画布*/
var shirtCvs = {};
var coatCvs = {};
var trouserCvs = {};
var bodyCvs = {};
var headCvs = {};
var bgCvs = {};
var accCvs = {};
var nCvs = {};
var allCvs1 = {};
var allCvs2 = {};
var allCvs3 = {};
window.tempCvs = {};

//存储模特身体的点
var modelBody = localStorage.getItem("modelBody");

//主函数
var fitting = (function(handler, options) {
	var fit = {};

	//更新参数
	fit.update = function(options) {
		renderNum = 0;
		$.extend(true, this.opts, options);
		this.render(this.opts.rotateType);
	};

	// 初始化入口
	fit.init = function() {
		renderNum = 0;
		cvsHeight = this.opts.cvsHeight;
		cvsWidth = this.opts.cvsWidth;
		$elem1 = $(this.opts.elem).eq(0);
		$elem2 = $(this.opts.elem).eq(1);
		$elem3 = $(this.opts.elem).eq(2);

		//自适应屏幕	（根据现在的结构， 今后可修改）
		var wHeight = $(window).height();
		cWidth = $(window).width();
		var hHeight = $(".header").height();
		var mHeight = $(".menu-list").height();
		cHeight = wHeight - hHeight - mHeight;

		// 添加画布
		nCvs.elem = $('<canvas width=' + cvsWidth + ' height=' + cvsHeight + ' id="n-canvas"/>')[0];
		shirtCvs.elem = $('<canvas width=' + cvsWidth + ' height=' + cvsHeight + ' id="shirt-canvas"/>')[0];
		coatCvs.elem = $('<canvas width=' + cvsWidth + ' height=' + cvsHeight + ' id="coat-canvas"/>')[0];
		trouserCvs.elem = $('<canvas width=' + cvsWidth + ' height=' + cvsHeight + ' id="trouserCvs-canvas"/>')[0];
		accCvs.elem = $('<canvas width=' + cvsWidth + ' height=' + cvsHeight + ' id="acc-canvas"/>')[0];
		bodyCvs.elem = $('<canvas width=' + cvsWidth + ' height=' + cvsHeight + ' id="body-canvas"/>')[0];
		headCvs.elem = $('<canvas width=' + cvsWidth + ' height=' + cvsHeight + ' id="head-canvas"/>')[0];      
		bgCvs.elem = $('<canvas width=' + cvsWidth + ' height=' + cvsHeight + ' id="bg-canvas"/>')[0];
		tempCvs.elem = $('<canvas width=' + cvsWidth + ' height=' + cvsHeight + ' id="temp-canvas"/>')[0];
		allCvs1.elem = $('<canvas width="' + cWidth + '" height="' + cHeight + '" id="all-canvas-1" class="all-canvas"/>')[0];
		allCvs2.elem = $('<canvas width="' + cWidth + '" height="' + cHeight + '"  id="all-canvas-2" class="all-canvas"/>')[0];
		allCvs3.elem = $('<canvas width="' + cWidth + '" height="' + cHeight + '"  id="all-canvas-3" class="all-canvas"/>')[0];

		//获取上下文
		trouserCvs.ctx = trouserCvs.elem.getContext('2d');
		shirtCvs.ctx = shirtCvs.elem.getContext('2d');
		coatCvs.ctx = coatCvs.elem.getContext('2d');
		accCvs.ctx = accCvs.elem.getContext('2d');
		bodyCvs.ctx = bodyCvs.elem.getContext('2d');
		headCvs.ctx = headCvs.elem.getContext('2d');
		bgCvs.ctx = bgCvs.elem.getContext('2d');
		tempCvs.ctx = tempCvs.elem.getContext('2d');
		nCvs.ctx = nCvs.elem.getContext('2d');
		allCvs1.ctx = allCvs1.elem.getContext('2d');


		allCvs3.ctx = allCvs3.elem.getContext('2d');

		// 添加画布 节点
		$elem1.append(allCvs1.elem);
		$elem2.append(allCvs2.elem);
		$elem3.append(allCvs3.elem);

		//渲染画布
		this.render(this.opts.rotateType);
	};

	fit.createCanvas = function() {
		
	}

	// 画布渲染
	fit.render = function(rotateType) {
		var that = this;
		var allLen = 0;
		var linLen = 0;
		this.BMI(this.opts.somato.weight, this.opts.somato.height);
		//遍历所有图片，渲染到画布
		for (key in that.opts.images) {
			var oopt = that.opts.images[key];
			for (okey in oopt) {
				if (oopt[okey]) {
					allLen++;
					textures[okey] = {};
					textures[okey].image = new Image();
					textures[okey].image.src = oopt[okey];
					textures[okey].image.setAttribute("class", key + "_" + okey);
					textures[okey].image.onload = function() {
						var allClass = this.getAttribute("class");
						var pClass = allClass.split("_")[0];
						var hClass = allClass.split("_")[1];

						//内衣裤
						if (pClass == "nSrc") {
							nCvs.ctx.drawImage(this, 0, 0, 780, 950, 0, 0, 780, 950);
							linLen++;

						// T-shirt
						} else if (pClass == "shirtSrc") { 							
							shirtCvs.ctx.drawImage(this, 0, 0, 780, 950, 0, 0, 780, 950);
							linLen++;

						// 外套
						} else if (pClass == "coatSrc") {
							coatCvs.ctx.drawImage(this, 0, 0, 780, 950, 0, 0, 780, 950);
							linLen++

						// 裤子
						} else if (pClass == "trouserSrc") {
							trouserCvs.ctx.drawImage(this, 0, 0, 780, 950, 0, 0, 780, 950);
							linLen++

						// 配饰
						} else if (pClass == "accSrc") {

							// 鞋子						
							if (hClass.match("shoes") != null) {
								accCvs.ctx.drawImage(this, 0, 0, 780, 950, 0, 0, 780, 950);
							} else {
								accCvs.ctx.drawImage(this, 0, 0, 780, 950, 0, 0, 780, 950);
							}
							linLen++;
						} else if (pClass == "bodySrc") {

							//头部
							if (hClass.match("head") != null) {
								if (this.width == 400) {
									headCvs.ctx.drawImage(this, 0, 0, 400, 950, 190, 0, 400, 950);
								} else {
									if (that.opts.sex == "man") {
										headCvs.ctx.drawImage(this, 0, 0, 175, 202, 308, 33, 175, 202);
									} else {
										headCvs.ctx.drawImage(this, 0, 0, 780, 950, 0, 0, 780, 950);
									}
								}

							// 身体
							} else {
								bodyCvs.ctx.drawImage(this, 0, 0, 780, 950, 0, 0, 780, 950);
							}
							linLen++;

						// 背景
						} else if (pClass == "bgSrc") {
							bgCvs.ctx.drawImage(this, 0, 0, 780, 950, 0, 0, 780, 950);
							linLen++;
						}

						// 渲染到临时画布
						if (linLen == allLen) {
							if (that.opts.images.shirtSrc.shirt_3 != "" && that.opts.images.shirtSrc.coat_3 != "") {
								that.magicWand(rotateType);
							} else {
								if (rotateType === 0) {
									that.sprite(allCvs1, rotateType);
								} else if (rotateType === 1) {
									that.sprite(allCvs2, rotateType);
								} else if (rotateType === 2) {
									that.sprite(allCvs3, rotateType);
								}
							}
						}
					}
				}
			}
		};
	};

	// 体型判断
	fit.BMI = function(weight, height) {
		var reg1 = /(.*\/fitting\/).*(\/.*\.png)/;
		var reg2 = /(.*\/fitting\/).*(\/).*(\/.*\.png)/;
		var BMI = weight / ((height / 100) * (height / 100));
		var len, xleft, yleft, yright, xright;
		if (BMI < 18.5) {
			this.opts.BMIType = "thin";
		} else if (BMI >= 18.5 && BMI < 24) {
			this.opts.BMIType = "norm";
		} else if (BMI >= 24.0 && BMI < 28) {
			this.opts.BMIType = "sfat";
		} else if (BMI >= 28) {
			this.opts.BMIType = "fat";
		}

		var bodySrc = this.opts.images.bodySrc;
		for (key in bodySrc) {
			bodySrc[key] = bodySrc[key].replace(reg2, "$1" + this.opts.sex + "$2" + this.opts.BMIType + "$3");
		}
		this.opts.images.bodySrc = bodySrc;

		var nSrc = this.opts.images.nSrc;
		for (key in nSrc) {
			nSrc[key] = nSrc[key].replace(reg2, "$1" + this.opts.sex + "$2" + this.opts.BMIType + "$3");
		}
		this.opts.images.nSrc = nSrc;

		var accSrc = this.opts.images.accSrc;
		for (key in accSrc) {
			accSrc[key] = accSrc[key].replace(reg1, "$1" + this.opts.sex + "$2");
		}

		this.opts.images.accSrc = accSrc;
	}

	//查找颜色
	fit.getBlanks = function(context, pointX, pointY, imgWidth, imgHeight) {
		var imageData = context.getImageData(0, 0, imgWidth, imgHeight);
		var vdata = imageData.data;

		function getRBG(x, y) {
			var offset = imgWidth * y + x;
			return {
				red: vdata[offset * 4],
				green: vdata[offset * 4 + 1],
				blue: vdata[offset * 4 + 2],
				opacity: vdata[offset * 4 + 3]
			};
		};

		for (var y = pointY - 1; y < imgHeight - pointY - 1; y++) {
			if (getRBG(pointX, y).opacity === 0) {
				return y;
			}
		}
	};

	//魔棒工具
	fit.magicWand = function(rotateType) {
		//左衣袖  -- 左衣服  -- 右衣袖 -- 右衣服
		var x1 = 300,
			y1 = 274,
			x2 = 345,
			x3 = 440,
			x4 = 494,
			y4 = 325,
			startY = 274,
			currentCvs, xx1, xx2, xx3, xx4;
		if (rotateType === 0) {
			currentCvs = allCvs1;
		} else if (rotateType === 1) {
			currentCvs = allCvs2;
		} else if (rotateType === 2) {
			var y = y1;
			y1 = y4;
			y4 = y;
			xx4 = cvsWidth - x1;
			xx3 = cvsWidth - x2;
			xx2 = cvsWidth - x3;
			xx1 = cvsWidth - x4;
			x1 = xx1;
			x2 = xx2;
			x3 = xx3;
			x4 = xx4;
			currentCvs = allCvs3;
		}

		// var leftArm = this.getBlanks(coatCvs.ctx, x1, y1, cvsWidth, cvsHeight);
		// var leftShirt = this.getBlanks(coatCvs.ctx, x2, startY, cvsWidth, cvsHeight);
		// var rightArm = this.getBlanks(coatCvs.ctx, x3, startY, cvsWidth, cvsHeight);
		// var rightShirt = this.getBlanks(coatCvs.ctx, x4, y4, cvsWidth, cvsHeight);

		// //暂无法解决 短袖外套遮罩情况
		// if (leftArm <= startY) {
		//     this.sprite();
		// } else {
		// 	if (leftArm >= leftShirt) {
		// 		leftArm = leftArm - startY;
		// 		leftShirt = leftShirt - startY;
		// 		rightArm = rightArm - startY;
		// 		rightShirt = rightShirt - startY;
		// 	} else {
		// 		leftShirt = leftArm = leftArm - startY;
		// 		rightShirt = rightArm = rightShirt - startY;
		// 	}
		// 	shirtCvs.ctx.clearRect(190, 182, 165, 92);
		// 	shirtCvs.ctx.clearRect(461, 182, 165, 92);
		// 	shirtCvs.ctx.clearRect(190, startY, 110, leftArm - 8);
		// 	shirtCvs.ctx.clearRect(300, startY, 45, leftShirt - 5);
		// 	shirtCvs.ctx.clearRect(440, startY, 43, rightArm - 5);
		// 	shirtCvs.ctx.clearRect(483, startY, 110, rightShirt - 5);
		// }
		
		this.sprite(currentCvs, rotateType);
	}

	//合并图片
	fit.sprite = function(currentCvs, rotateType) {
		tempCvs.ctx.clearRect(0, 0, cvsWidth, cvsHeight);
		for (var i = 0; i < 9; i++) {
			if (i === 0) {
				tempCvs.ctx.drawImage(bgCvs.elem, 0, 0);
			} else if (i === 1) {
				tempCvs.ctx.drawImage(bodyCvs.elem, 0, 0);
			} else if (i === 2) {
				tempCvs.ctx.drawImage(headCvs.elem, 0, 0);
			} else if (i === 3) {
				tempCvs.ctx.drawImage(nCvs.elem, 0, 0);
			} else if (i === 4) {
				tempCvs.ctx.drawImage(trouserCvs.elem, 0, 0);
			} else if (i === 5) {
				tempCvs.ctx.drawImage(shirtCvs.elem, 0, 0);
			} else if (i === 6) {
				tempCvs.ctx.drawImage(accCvs.elem, 0, 0);
			} else if (i === 7) {
				tempCvs.ctx.drawImage(coatCvs.elem, 0, 0);
			} else if (i === 8) {
				// 模特身高问题
				// var newHeight = this.opts.somato.height * rate;
				// var newWidth = cvsWidth / cvsHeight * newHeight;

				trouserCvs.ctx.clearRect(0, 0, cvsWidth, cvsHeight);
				coatCvs.ctx.clearRect(0, 0, cvsWidth, cvsHeight);
				shirtCvs.ctx.clearRect(0, 0, cvsWidth, cvsHeight);
				accCvs.ctx.clearRect(0, 0, cvsWidth, cvsHeight);
				bgCvs.ctx.clearRect(0, 0, cvsWidth, cvsHeight);
				nCvs.ctx.clearRect(0, 0, cvsWidth, cvsHeight);
				bodyCvs.ctx.clearRect(0, 0, cvsWidth, cvsHeight);
				headCvs.ctx.clearRect(0, 0, cvsWidth, cvsHeight);
				currentCvs.ctx.clearRect(0, 0, cvsWidth, cvsHeight);
				// 模特身高问题
				// currentCvs.ctx.drawImage(tempCvs.elem, (cvsWidth - newWidth) / 2, cvsHeight - newHeight, newWidth, newHeight);

				//适应容器
				var nWidth = cHeight * cvsWidth / cvsHeight;
				var nLeft = (cWidth - nWidth) / 2;
				currentCvs.ctx.drawImage(tempCvs.elem, 0, 0, cvsWidth, cvsHeight, nLeft, 0, nWidth, cHeight);

				tempCvs.ctx.clearRect(0, 0, cvsWidth, cvsHeight);
				if (renderNum < 3) {
					if (rotateType === 0) {
						this.render(1);
					} else if (rotateType === 1) {
						this.render(2);
					} else if (rotateType === 2) {
						this.render(0);
					}
					renderNum++;
				}
			}
		}
	};

	function fitting(options) {
		// 参数
		this.opts = {};

		// 合并参数
		$.extend(true, this.opts, opts, options);
	}

	fitting.prototype = fit;
	return fitting;

})();

//实现jquery
$.fn.fitting = function(options) {
	if (!this.fittingInstance) {
		this.fittingInstance = new fitting(this, options || {});
	} else {
		this.fittingInstance.update(options || {});
	}
	this.fittingInstance.init();
};